package handler

import (
	"die4.4/api/request"
	"die4.4/model"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"net/http"
)

func Register(c *gin.Context) {
	var data request.User
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "参数错误",
			"Data": nil,
		})
		return
	}

	u := model.User{
		Name:     data.Name,
		Password: data.Password,
	}
	err = u.Register()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "注册失败",
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "成功",
		"Data": nil,
	})
}

func Login(c *gin.Context) {
	var data request.User
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "参数错误",
			"Data": nil,
		})
		return
	}
	u := model.User{}
	login, err := u.Login(data.Name, data.Password)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "登录失败",
			"Data": nil,
		})
		return
	}
	token, err := jwt.NewJWT("zj").CreateToken(jwt.CustomClaims{ID: login.ID})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "token 生成失败",
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "成功",
		"Data": token,
	})
}

func UserList(c *gin.Context) {
	u := model.User{}
	list, err := u.UserList()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "展示失败",
			"Data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "成功",
		"Data": list,
	})
}
